package cn.mumzone.basic.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;

import java.lang.ref.WeakReference;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Author Chaney
 * Date   2017/3/14 下午4:48.
 * EMail  qiuzhenhuan.hi@gmail.com
 */

public abstract class SimpleActivity extends AppCompatActivity {

    public MyHandler mHandler = new MyHandler(this);
    protected Activity mContext;
    private Unbinder mUnbinder;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        if (getLayout() != 0) {
            setContentView(getLayout());
        }
        mUnbinder = ButterKnife.bind(this);
        mContext = this;
        initVariable();
        initEventAndData();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mUnbinder != Unbinder.EMPTY) {
            mUnbinder.unbind();
        }
    }

    protected abstract void initVariable();

    protected abstract void initEventAndData();

    protected abstract int getLayout();


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        if (fragments != null && !fragments.isEmpty()) {
            for (Fragment fragment : fragments) {
                fragment.onActivityResult(requestCode, resultCode, data);
            }
        }
    }

    /**
     * 使用软引用的 Handler
     * 避免不当操作导致的内存泄漏
     */
    public static class MyHandler extends Handler {
        private WeakReference<SimpleActivity> mActivity;

        public MyHandler(SimpleActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            if (mActivity.get() != null) {
                mActivity.get().handleMsg(msg);
            }
        }
    }

    protected void handleMsg(Message msg) {
    }

}